package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.IProductService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Override
    public List<Product> selectProductList() {
        return baseMapper.selectProductList();
    }

    /**
     * 保存商品（SPU、SKU列表、SPU详情、库存）
     * 事务特性：
     * 1.原子性
     * 2.隔离性 读未提交（脏读、不可重复读、幻读）、读已提交(默认)（不可重复读、幻读）、可重复读（幻读）、串行化（解决所有读问题）
     * 3.一致性
     * 4.持久层 底层基于RedoLog日志记录，保证数据持久化
     *
     * @param product
     * @return
     */
    @Autowired
    private ProductDetailsMapper productDetailsMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private SkuStockMapper skuStockMapper;

    @Override
    @Transactional(rollbackFor = Exception.class) //默认发生 RuntimeException,Error运行时异常 会进行事务回滚
    public int insertProduct(Product product) {


        //1.新增商品SPU信息
        //1.1设置商品初始化状态0 未上架 1 上架
        product.setStatus(0);
        //1.2设置商品创建人
        product.setCreateBy(SecurityUtils.getUsername());
        //1.3保存商品信息
        baseMapper.insert(product);
        //1.4获取商品id
        Long productId = product.getId();

        //2.新增商品详情信息
        //2.1构建商品详情对象
        ProductDetails productDetails = new ProductDetails();
        //2.2获取商品对象详情图片的列表
        List<String> detailsImageUrlList = product.getDetailsImageUrlList();
        if (!CollectionUtils.isEmpty(detailsImageUrlList)) {
            String imageUrL = String.join(",", detailsImageUrlList);
            productDetails.setImageUrls(imageUrL);
        }
        //2.3关联商品id
        productDetails.setProductId(productId);
        //2.4保存商品详细信息
        productDetailsMapper.insert(productDetails);
        //3.批量新增商品SKU信息 新增商品库存信息
        //3.1获取商品SKU列表
        List<ProductSku> SkuList = product.getProductSkuList();
        if (!CollectionUtils.isEmpty(SkuList)) {
            int num = 1;
            for (ProductSku sku : SkuList) {
                //3.2保存SKU信息

                //3.2.1生成商品的sku编号 商品id_1
                sku.setSkuCode(productId + "_" + num++);
                //3.2.2生成商品的名称名称 规则:商品名称+规格参数
                sku.setSkuName(product.getName() + " " + sku.getSkuSpec());
                //3.2.3关联SPUID
                sku.setProductId(productId);
                //3.2.4设置状态
                sku.setStatus(0);
                //3.2.5设置创建者
                sku.setCreateBy(SecurityUtils.getUsername());
                //3.2.6保存SKUID
                productSkuMapper.insert(sku);
                //3.2.7获取SKUID
                Long skuId = sku.getId();

                //3.3保存SKU库存
                SkuStock skuStock = new SkuStock();
                skuStock.setSkuId(skuId);
                skuStock.setTotalNum(sku.getStockNum());
                skuStock.setAvailableNum(sku.getStockNum());
                skuStock.setLockNum(0);
                skuStock.setSaleNum(0);
                skuStock.setStatus(0);
                skuStock.setCreateBy(SecurityUtils.getUsername());
                skuStockMapper.insert(skuStock);

            }
            //
        }
        return 1;
    }

    /**
     * 商品上架或下架
     *
     * @param spuId
     * @param status
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//事务回滚
    public void updateStatus(Long spuId, Integer status) {
        //1.商品状态SPU状态
        Product product = new Product();
        product.setId(spuId);
        product.setStatus(status);
        product.setUpdateBy(SecurityUtils.getUsername());
        baseMapper.updateById(product);
//        2.商品SKU状态
//        ProductSku productSku = new ProductSku();
//        productSku.setStatus(status);
//        productSku.setUpdateBy(SecurityUtils.getUsername());
//        productSkuMapper.update(productSku,
//                new LambdaUpdateWrapper<ProductSku>().eq(ProductSku::getProductId,spuId));
        LambdaUpdateWrapper<ProductSku> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ProductSku::getProductId, spuId);
        updateWrapper.set(ProductSku::getStatus, status);
        productSkuMapper.update(null, updateWrapper);
//        3.商品库存状态
        //3.1查询商品SKUID列表
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, spuId)
                .select(ProductSku::getId);
        List<Long> skuIdList = productSkuMapper.selectList(queryWrapper)
                .stream().map(ProductSku::getId)
                .collect(Collectors.toList());


        //3.2更新状态
        LambdaUpdateWrapper<SkuStock> stockLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        stockLambdaUpdateWrapper.set(SkuStock::getStatus, status);
        stockLambdaUpdateWrapper.in(SkuStock::getSkuId, skuIdList);
        skuStockMapper.update(null, stockLambdaUpdateWrapper);
    }

    /**
     * 删除商品
     *
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteProductByIds(List<Long> ids) {
        //1.删除商品SPU表
        baseMapper.deleteBatchIds(ids);

        //2.获取商品SPUID查询SKUID
        LambdaQueryWrapper<ProductSku> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductSku::getProductId, ids).select(ProductSku::getId);
        List<ProductSku> productSkusList = productSkuMapper.selectList(queryWrapper);
//        List<ProductSku> productSkusList = productSkuMapper.selectList(
//                new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, ids)
//                        .select(ProductSku::getId));
        if (!CollectionUtils.isEmpty(productSkusList)) {

            List<Long> skuIDList = productSkusList
                    .stream()
                    .map(ProductSku::getId)
                    .collect(Collectors.toList());
            //3.删除商品SKU表
            productSkuMapper.deleteBatchIds(skuIDList);
            //4.删除商品SKU库存表
            //4.1获取SKU库存id
//方法1
//            LambdaQueryWrapper<SkuStock> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//            lambdaQueryWrapper.eq(SkuStock::getSkuId,skuIDList);
//            List<SkuStock> skuStocks = skuStockMapper.selectList(lambdaQueryWrapper);
//            skuStockMapper.deleteBatchIds(skuStocks);
            //方法2.
//            skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getStatus,skuIDList)
//                    .select(SkuStock::getId)
//            );
            //方法3最省事
            skuStockMapper.delete
                    (new LambdaQueryWrapper<SkuStock>()
                            .in(SkuStock::getSkuId, skuIDList));

            //5.删除商品详情表
            productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>()
                    .in(ProductDetails::getProductId, ids));


        }


    }


}
